<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import type { ApiStateInput, ApiSysEmailSendTemplateOut, ApiSysEmailSendTemplateQuery, ApiUserOut, ApiUserQuery } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { SysemailsendtemplateApi } from '@/api-services/apis/sysemailsendtemplate-api';
import { yesOrNoRecord } from '@/constants/common';
import { ElButton, ElPopconfirm, ElSwitch, ElTag } from 'element-plus';
import { NetoKit } from '@/typings/neto';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysEmailSendTemplateQuery) =>
  fetchTableQuery<ApiSysEmailSendTemplateQuery, ApiSysEmailSendTemplateOut>(params,
    (internalParams: ApiSysEmailSendTemplateQuery) =>
      getAPI(SysemailsendtemplateApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    startDate: undefined,
    endDate: undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 230,
      align: 'center',
    },

    {
      prop: 'code',
      //dataIndex: 'code',
      label: $t('page.emailManage.emailTemplate.code'),
      align: 'center',
      minWidth: 120
    },
    {
      prop: 'templateType',
      //dataIndex: 'templateType',
      label: $t('page.emailManage.emailTemplate.templateType'),
      align: 'center',
      minWidth: 230,
      formatter: record => {
        if (record.templateType === null) {
          return '';
        }
        let templateTypeName = '';

        switch (record.templateType) {
          case 1001:
            //会员注册
            templateTypeName = $t('page.emailManage.emailTemplate.templateTypeEnum.register');
            break;
          case 1002:
            //会员修改密码
            templateTypeName = $t('page.emailManage.emailTemplate.templateTypeEnum.updatePwd');
            break;
          case 1003:
            //会员修改邮箱
            templateTypeName = $t('page.emailManage.emailTemplate.templateTypeEnum.updateEmail');
            break;
          case 1004:
            //会员重置密码
            templateTypeName = $t('page.emailManage.emailTemplate.templateTypeEnum.resetPwd');
            break;
        }


        return <ElTag type="success">{templateTypeName}</ElTag>;
      }
    },
    {
      prop: 'title',
      //dataIndex: 'title',
      label: $t('page.emailManage.emailTemplate.title'),
      align: 'center',
      minWidth: 130
    },
    // {
    //   prop: 'content',
    //   //dataIndex: 'content',
    //   label: $t('page.emailManage.emailTemplate.content'),
    //   align: 'center',
    //   minWidth: 250,
    //   ellipsis: true,
    //   formatter: record => {
    //     if (!record.content) {
    //       return null;
    //     }

    //     //直接显示代码蚊子
    //     return <div>{record.content}</div>
    //     //渲染成html
    //     // return <div v-html={record.content.substring(0, 100)}></div>;
    //   }
    // },
    {
      prop: 'isVerCode',
      //dataIndex: 'isVerCode',
      label: $t('page.emailManage.emailTemplate.isVerCode'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isVerCode === null) {
          return '';
        }
        const hide: CommonType.YesOrNo = record.isVerCode ? 'Y' : 'N';

        const tagMap: Record<CommonType.YesOrNo, NetoKit.TagType> = {
          Y: 'danger',
          N: 'info'
        };

        const label = $t(yesOrNoRecord[hide]);

        return <ElTag type={tagMap[hide]}> {label} </ElTag>;
      }
    },
    // 是否启用
    {
      prop: 'isEnable',
      //dataIndex: 'isEnable',
      label: $t('page.manage.common.isEnable'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }
        const handleSwitchChange = async (checked: boolean | string | number) => {
          if (!record.id) {
            return;
          }
          // 提交请求
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: true
          };
          const [err, res] = await feature(getAPI(SysemailsendtemplateApi).setIsEnable(record.id, Boolean(checked)));
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isEnable = Boolean(checked);
            } else {
              window.$message?.error($t('common.failed'));
            }
          });
        };
        return (
          <ElSwitch
            modelValue={record.isEnable}
            onChange={handleSwitchChange}
            loading={loadingStates.value[record.id!] || false}
          ></ElSwitch>
        );
      }
    },


    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //修改时间
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      minWidth: 230,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id!)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  //rowSelection,
  onBatchDeleted,
  onDeleted
} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {
  const ids = [];

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendtemplateApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (checkedRowKeys.value == undefined || checkedRowKeys.value.length == 0) {
    return;
  }
  const ids = checkedRowKeys.value?.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendtemplateApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error('删除失败');
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.emailManage.emailTemplate.titleList') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
